<?php

namespace app\common\controller;

use think\Controller;
use think\exception\ValidateException;

class Base extends Controller {
	/**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    protected $noNeedLogin = [];
    protected $loader = '';
    protected $process = null;
    protected $response = 'Base';

    protected function _initialize() {
        $this->loader = loader($this->loader);
        $this->response = $this->loader->loadAny('response', $this->response);
        $this->validate_login();
        $this->process = $this->init_process($this->process);
    }

    protected function init_process($process) {
        if(is_string($process)) {
            $process = $this->loader->loadProcess($process);
        } else if(is_array($process)) {
            $processName = array_shift($process);
            $process = $this->loader->loadProcess($processName, $process);
        }
        return $process;
    }

    //登陆验证
    protected function validate_login() {
        $noNeedLogin = $this->noNeedLogin;
        $loginData = [];

        if(!in_array('*', $noNeedLogin) && !in_array($this->request->action(), $noNeedLogin)) {
            $loginData['login'] = true;
        }
        $validate = loadValidate('Login');
        if(!$validate->check($loginData)){
            $this->no_login($validate->getError());
        }
    }

    protected function get_login() {
        return loadStorage('Login');
    }

    protected function ajax_process($fun, $process = null, $isReturn = false) {
        $user = $this->get_login()->getCurrentUser();
        $msg = '';
        if(!$process) {
            $process = $this->process;
        } else {
            $process = $this->init_process($process);
        }
        try {
            $args = $fun($process, $user);
        } catch(ValidateException $e) {
            $this->error($e->getError());
        }
        if(!$isReturn) {
            if(isset($args['__msg'])) {
                $msg = $args['__msg'];
                unset($args['__msg']);
            }
            $this->success($msg, $args);
        } else {
            return $args;
        }
    }

    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->response->result($msg, $data, $code, $type, $header);
    }

    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->response->result($msg, $data, $code, $type, $header);
    }

    protected function no_login($msg = '', $data = null, $code = -1, $type = null, array $header = [])
    {
        $this->response->result($msg, $data, $code, $type, $header);
    }

    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->response->result($msg, $data, $code, $type, $header);
    }
}
